﻿#include "loginsemaphore.h"
#include <QApplication>
#include <QCryptographicHash>
#include <QRegExp>
#include <QSystemSemaphore>

LoginSemaphore::LoginSemaphore():semaphore_(Q_NULLPTR)
{
}

LoginSemaphore::~LoginSemaphore()
{
    cleanAll();
}

bool LoginSemaphore::tryAcquire(int account_type, const QString &account)
{
    const QString key = QApplication::applicationName()+'_'+QString::number(account_type)+'='+account;
    if(semaphore_map.contains(key))
        return true;
    cleanHandle();
    semaphore_ = new QSystemSemaphore(key, 1, QSystemSemaphore::Open);
    start();
    wait(1000);
    if(isRunning() || semaphore_->error() != QSystemSemaphore::NoError)
    {
        cleanRunning();
        return false;
    }
    semaphore_map[key] = semaphore_;
    semaphore_ = Q_NULLPTR;
    return true;
}

void LoginSemaphore::cleanHandle()
{
    if(isRunning())
    {
        terminate();
        wait(1000);
    }
    if(semaphore_){
        delete semaphore_;
        semaphore_ = Q_NULLPTR;
    }
}

void LoginSemaphore::cleanAll()
{
    cleanRunning();
    qDeleteAll(semaphore_map);
    semaphore_map.clear();
}

void LoginSemaphore::run()
{
    semaphore_->acquire();
}

void LoginSemaphore::cleanRunning()
{
    if(isRunning())
    {
        terminate();
        wait(1000);
    }
    if(semaphore_){
        delete semaphore_;
        semaphore_ = nullptr;
    }
}
